package com.jiuzhe.commercial.http;

import android.os.Handler;
import android.os.Looper;

import com.blankj.utilcode.utils.NetworkUtils;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/3/1.
 */
public class HttpClient2 {
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private static final String RET_CODE = "status";
    private static final String MESSAGE = "message";
    private static final String RESULT = "data";
    private static Handler handler = new Handler(Looper.getMainLooper());
    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new LoggingInterceptor())
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(100, TimeUnit.SECONDS)
            .build();


    /**
     * post请求
     *
     * @param tag
     * @param url
     * @param map
     * @param callBack
     */
    public static void post(Object tag, String url, HashMap<String, String> map, final CallBack callBack) {
        if (!NetworkUtils.isAvailableByPing()) {
            callBack.onFailure(5, "请检查网络状态！");
            return;
        }
        FormBody.Builder builder = new FormBody.Builder();
        //builder.add(DATA, new Gson().toJson(map));
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, new Gson().toJson(map));

        if (map != null && map.containsKey("token") && map.containsKey("sign")) {
            url += "?";
            Iterator<String> iterator = map.keySet().iterator();// map中key（键）的迭代器对象
            while (iterator.hasNext()){// 循环取键值进行判断
                String key = iterator.next();// 键
                if(key.startsWith("token")){
                    String value = map.get(key);
                    url += key + "=" + value + "&";
                    iterator.remove();// 移除map中以taken字符开头的键对应的键值对
                }
                if(key.startsWith("sign")) {
                    String value = map.get(key);
                    url += key + "=" + value + "&";
                    iterator.remove();// 移除map中以sign字符开头的键对应的键值对
                }
            }
        }

        // 去掉最后一个空格
       // url = url.substring(0, url.length() - 1);

        Logger.json(new Gson().toJson(map));
        Request request = new Request.Builder()
                .tag(tag)
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(-1, e.getLocalizedMessage());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handlerResponse(response, callBack);
            }
        });
    }


    public static void post2(Object tag, String url, HashMap<String, Object> map, final CallBack callBack) {
        if (!NetworkUtils.isAvailableByPing()) {
            callBack.onFailure(5, "请检查网络状态！");
            return;
        }
        FormBody.Builder builder = new FormBody.Builder();
        //builder.add(DATA, new Gson().toJson(map));
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, new Gson().toJson(map));

         Logger.json(new Gson().toJson(map));
        Request request = new Request.Builder()
                .tag(tag)
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handlerResponse(response, callBack);
            }
        });
    }


    public static void get(Object tag, String url, HashMap<String, String> map, final CallBack callBack) {
        if (!NetworkUtils.isAvailableByPing()) {
            callBack.onFailure(5, "网络开小差了,请检查网络！");
            return;
        }
        if (map != null && map.size() >0) {
            url += "&";
            for (String key : map.keySet()) {
                String value = map.get(key);
                url += key + "=" + value + "&";
            }
        }
        // 去掉最后一个空格
     //   url = url.substring(0, url.length() - 1);


        Request request = new Request.Builder()
                .tag(tag)
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(-1, e.getLocalizedMessage());
                    }
                });
            }

            @Override
            public void onResponse(final Call call, Response response) throws IOException {
                handlerResponse(response, callBack);
            }
        });
    }

    /**
     * 根据tag取消请求
     *
     * @param tag 标签
     */
    public static void cancelRequest(Object tag) {
        for (Call call : okHttpClient.dispatcher().queuedCalls()) {
            if (call.request().tag().equals(tag)) {
                call.cancel();
            }
        }
    }


    private static void handlerResponse(Response response, final CallBack callBack) throws IOException {

        //看清楚是response.body().string()不是response.body().toString()
        String json = response.body().string();
        //json = json.replace("null", "\"\"");
        Logger.json(json);
        final String finalJson = json;
        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    callBack.onSuccess(new Gson().fromJson(finalJson, callBack.type));

                } catch (Exception e) {
                    e.printStackTrace();
                    callBack.onFailure(-1, e.getLocalizedMessage());
                }
            }
        });
    }

    /**
     * 请求响应日志信息，方便debug
     */
    public static class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long t1 = System.nanoTime();
            Logger.i(String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));

            Response response = chain.proceed(request);
            long t2 = System.nanoTime();

            Logger.i(String.format("Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers()));
            return response;
        }
    }
}
